package com.heima.kafka.simple;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者开始
 *
 * @author DiXiaoNie
 * @date 2022/12/28
 * @since 2022/12/28 11:16
 */

public class ConsumerStart {
    public static void main(String[] args) {
        //2.设置kafka配置信息
        //2.设置kafka配置信息
        Properties properties = new Properties();
        //2.1 kafka地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.56.130:9092");
        //2.2 设置对key value进行字符串序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //加入一个组id
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group2");

        //1.创建消费对像
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer(properties);

        //3.订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("kafka-stream-consumer"));

        //3.订阅主题
        while (true) {
            //4.拉取消息
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(10));//指定是10ms拉取一次
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.key() + ":" + record.value());
            }
        }

    }
}
